<template>
  <div class="search-container">
    <!-- 搜索框 -->
    <div class="search-header">
      <div class="search-box">
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索" 
          class="search-input"
          @keyup.enter="handleSearch"
          @input="handleInput"
        />
      </div>
      <button class="cancel-btn" @click="goBack">取消</button>
    </div>

    <!-- 搜索历史 -->
    <div v-if="showHistory" class="search-section">
      <div class="section-header">
        <span class="section-title">搜索历史</span>
        <button class="clear-btn" @click="clearHistory">🗑️</button>
      </div>
      <div v-if="searchHistory.length > 0" class="tags-container">
        <div 
          v-for="(item, index) in searchHistory" 
          :key="index" 
          class="tag"
          @click="searchFromHistory(item)"
        >
          {{ item }}
        </div>
      </div>
      <div v-else class="empty-state">
        <p>暂无搜索历史</p>
      </div>
    </div>

    <!-- 热门搜索 -->
    <div class="search-section">
      <div class="section-header">
        <span class="section-title">热门搜索</span>
      </div>
      <div class="tags-container">
        <div 
          v-for="(item, index) in hotSearches" 
          :key="index" 
          class="tag"
          @click="searchFromHot(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <div class="section-header">
        <span class="section-title">搜索结果</span>
      </div>
      <div class="results-list">
        <div 
          v-for="item in searchResults" 
          :key="item.id" 
          class="result-item"
          @click="viewDetail(item)"
        >
          <div v-if="item.media_urls && item.media_urls.length > 0" class="result-image">
            <img :src="item.media_urls[0]" :alt="item.title">
          </div>
          <div class="result-content">
            <h3 class="result-title">{{ item.title }}</h3>
            <p class="result-desc">{{ item.content.substring(0, 80) }}...</p>
            <div class="result-meta">
              <span class="author">@{{ item.author_nickname }}</span>
              <span class="likes">👍 {{ item.like_count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/api'

const router = useRouter()
const searchKeyword = ref('')
const showHistory = ref(true)
const searchHistory = ref([])
const searchResults = ref([])
const loading = ref(false)

// 热门搜索词
const hotSearches = ref([
  '美食',
  '旅行',
  '摄影',
  '萌宠',
  '美妆',
  '健身',
  '穿搭',
  '手工',
  '探店',
  'DIY'
])

// 从本地存储加载搜索历史
onMounted(() => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
})

// 搜索输入处理
const handleInput = () => {
  // 如果输入框有内容，隐藏搜索历史
  showHistory.value = searchKeyword.value === ''
}

// 从历史记录搜索
const searchFromHistory = (keyword) => {
  searchKeyword.value = keyword
  handleSearch()
}

// 从热门搜索搜索
const searchFromHot = (keyword) => {
  searchKeyword.value = keyword
  handleSearch()
}

// 执行搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    return
  }

  loading.value = true

  // 保存搜索历史
  addToHistory(searchKeyword.value)

  try {
    const token = localStorage.getItem('token')
    
    const response = await axios.post('/api/search/content', {
      keyword: searchKeyword.value,
      limit: 20
    }, {
      headers: {
        'Authorization': token ? `Bearer ${token}` : ''
      }
    })

    if (response.data.success) {
      searchResults.value = response.data.data
    } else {
      searchResults.value = []
    }
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
  } finally {
    loading.value = false
    showHistory.value = false
  }
}

// 添加到搜索历史
const addToHistory = (keyword) => {
  if (!keyword.trim()) return
  
  const index = searchHistory.value.indexOf(keyword)
  if (index > -1) {
    // 如果已存在，移到最前面
    searchHistory.value.splice(index, 1)
  }
  
  // 添加到最前面
  searchHistory.value.unshift(keyword)
  
  // 最多保存10条
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }
  
  // 保存到本地存储
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.setItem('searchHistory', '[]')
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 查看详情
const viewDetail = (item) => {
  console.log('查看详情:', item)
  // TODO: 跳转到详情页
}
</script>

<style scoped>
.search-container {
  width: 100vw;
  min-height: 100vh;
  background: #f5f5f5;
}

/* 搜索框 */
.search-header {
  background: white;
  padding: 10px 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-box {
  flex: 1;
}

.search-input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  outline: none;
  font-size: 14px;
}

.cancel-btn {
  background: none;
  border: none;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  padding: 5px 10px;
}

/* 区块标题 */
.search-section {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-title {
  color: #999;
  font-size: 12px;
}

.clear-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
}

/* 标签容器 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag {
  background: #f5f5f5;
  padding: 8px 15px;
  border-radius: 20px;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.tag:hover {
  background: #e0e0e0;
}

.empty-state {
  text-align: center;
  color: #999;
  font-size: 12px;
  padding: 20px;
}

/* 搜索结果 */
.search-results {
  padding: 15px;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.result-item {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
  display: flex;
  gap: 10px;
  padding: 10px;
}

.result-item:hover {
  transform: translateY(-2px);
}

.result-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
}

.result-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.result-content {
  flex: 1;
}

.result-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.result-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.result-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

.author {
  color: #007AFF;
}
</style>

